<template>
    <div class="comFlex">
        <div class="leftDiv">
            <el-input v-model="searchMenu" class="comTop10 comLeft8" style="width: 180px" placeholder="请输入" />  
            <el-tree
                style="max-width: 180px"
                :data="treeData"
                :props="defaultProps"
                accordion
                @node-click="handleNodeClick"
            >
            <template #default="{ node }">
             <el-icon><Folder /></el-icon>
              <span style="margin-left: 10px;">{{ node.label }}</span>
            </template>
          </el-tree>
        </div>
        <div class="rightDiv comLeft25">
          <div style="padding-top: 30px;padding-left: 18px;">
             <el-row :gutter="24">
              <el-col :span="8">
                <div class="comFlex comFlexCenter">
                  <label class="wordNoBreak textRight comWidth78">用户名:</label><el-input v-model="uName" class="comWidth400"></el-input>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="comFlex comFlexCenter">
                  <label class="wordNoBreak textRight comWidth78">用户昵称:</label><el-input v-model="nickName" class="comWidth400"></el-input>
                </div>
              </el-col>
              <el-col :span="8">
                <el-button type="primary" :icon="Search" @click="getUserData">查询</el-button>
                <el-button :icon="RefreshRight" @click="reset">重置</el-button>
              </el-col>
            </el-row>
             <el-row :gutter="24" class="comTop6">
              <el-col :span="8">
                <div class="comFlex comFlexCenter">
                  <label class="wordNoBreak textRight comWidth78">状态:</label>
                  <el-select
                    v-model="status"
                    placeholder="请选择"
                    size="large"
                  >
                    <el-option
                      v-for="item in statusOpt"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="comFlex comFlexCenter">
                  <label class="wordNoBreak textRight comWidth78">手机号:</label><el-input class="comWidth400" v-model="phone"></el-input>
                </div>
              </el-col>
            </el-row>
            <div class="comTop20">
              <el-button round v-for="(item,i) in btnList" :key="i" :type="item.type" @click="item.func">
                {{ item.label }}
              </el-button>
            </div>
          </div>
            <Table @handleSizeChange="getUserData" v-model:page="page" v-model:size="size" :total="totalData" :columns="tableColumns" :tableData="tableData" class="comTop10" style="padding-left: 20px;">
                <template #status="scope">
                    <!-- lockFlag = 9 为禁用 -->
                     <el-switch
                        @change ='chageStatus(scope.row)'
                        :value="scope.row.lockFlag"
                        class="ml-2"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                    />
                </template>
                 <template #opt="scope">
                    <el-button @click="item.func(scope)" :type="item.type" link v-for="(item,i) in btnArr" :key="i">
                        {{ item.label }}
                    </el-button>
                </template>
            </Table>
        </div>
        <comForm ref="formRefs" :rules="formRules" @save="saveForm" :popupWidth="650" @cancel="cancel" :value="formValue" v-model:dialogVisible="dialogVisible" :dialogTitle="dialogTitle" :formConfig="formConfig">

        </comForm>
         <el-dialog
            v-model="delVisible"
            :title="visibleTitle"
            width="500"
            :before-close="handleClose"
          >
        <h2>{{ dialogDetail }}</h2>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="delVisible = false">取消</el-button>
            <el-button type="primary" @click="deleFun">
              确认
            </el-button>
          </div>
        </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { Folder } from '@element-plus/icons-vue'
import comForm from '@/components/comForm.vue'
import {resetForm ,getValue, getLabel} from '@/tools/tools.js'
import Table from '@/components/Table.vue'
import { computed, onMounted, reactive, ref } from 'vue'
import { UserService } from '@/api/api'
import { RefreshRight, Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
const formRefs = ref(null)
const visibleTitle = ref('')
const dialogDetail = ref('')
const delVisible = ref(false)
const dialogVisible = ref(false)
const totalData = ref(0)
const status = ref('')
const reset = () => {
  uName.value = nickName.value = status.value = phone.value = ''
  getUserData()
}
const currentVisId = ref(0)
const currentName = ref('')
const chageStatus = (val) => {
  currentName.value = val.username
  delVisible.value = true
  currentVisId.value = 1
  visibleTitle.value = '禁用'
  dialogDetail.value = '是否禁用'
}
const statusOpt = ref([
  {
    label : '启用',
    value : '0'
  },
  {
    label : '禁用',
    value : '1'
  }
])
const deptName = ref('')
const size = ref(10)
const page = ref(1)
const statusList = ref([])
const uName = ref('')
const nickName = ref('')
const deptList = ref([])
const phone = ref('')
const formValue = reactive({
  username : '',
  nickname : '',
  password :'',
  phone : '',
  name : '',
  email : '',
  role : null,
  lockFlag : '0',
  deptId : '',
})
const currentDeptId = ref('')
const getSelectList = () => {
  UserService.getRoleList().then(res => {
    statusList.value = []
    if(res.code == 0){
      res.data.forEach(item => {
        statusList.value.push({
          label : item.roleName,
          value : item.roleId
        })
      })
    }
  })
}
const getSelectOptList = () => {
  UserService.getDeptList().then(res => {
    if(res.code == 0){
      deptList.value = []
      res.data.forEach(item => {
        deptList.value.push({
          label : item.name,
          value : item.deptId
        })
      })
    }
  })
}
//部门列表
const currentDept = computed(() => {
  return deptList
})

const currentOpt = computed(() => {
  return statusList
})
const saveForm = () => { 
  if(isAdd.value == false){
    formValue.deptId = parseInt(getValue(deptList.value, formValue.deptId)) 
    formValue.role = parseInt(getValue(statusList.value, formValue.role)) 
    formValue.role = [formValue.role]
    UserService.updateUserInfo({...formValue}).then(res => {
      if(res.code == 0){
        ElMessage.success('更新成功!')
        resetForm(formValue)
        dialogVisible.value = false
        getUserData()
      }
    })
  }else{
    formValue.role = [parseInt(formValue.role)]
    // formValue.deptId = `${currentDeptId.value}`
    UserService.addUser({...formValue}).then(res => {
      if(res.code == 0){
        ElMessage.success('新增用户成功!')
        resetForm(formValue)
        dialogVisible.value = false
        getUserData()
      }
    })
  }
}
onMounted(() => {
  getSelectOptList()
  getSelectList()
  getMenu()
})
const validTel = (rule,value,callback) => {
    if(value === ''){
        callback(new Error('手机号不能为空'))
    }else{
        const phoneReg = /^1[34578]\d{9}$/
        phoneReg.test(value) ? callback() : callback(new Error('手机号格式不正确，请输入正确手机号'))
    }
}
const validEmail = (rule,value,callback) => {
   if(value === ''){
        callback(new Error('手机号不能为空'))
    }else{
        const phoneReg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        phoneReg.test(value) ? callback() : callback(new Error('手机号格式不正确，请输入正确手机号'))
    }
}
const formRules = reactive(
  {
    phone : [
      {
        trigger : 'blur',
        validator : validTel
      }
    ],
    role : [
      {
        required : true
      }
    ],
    deptId : [
      {
        required : true
      }
    ]
    // email:[
    //   {
    //     validator : validEmail,
    //     trigger : 'blur',
    //   }
    // ]
  }
)
const getMenu = () => {
  let params = {
    deptName : deptName.value,
  }
  UserService.getTree(params).then(res => {
    const { code ,data} = res
    if(code == 0){
      treeData.value = data
      currentDeptId.value = data[0].id
      getUserData()
    }
  })
}
const formConfig = reactive({
  labelWidth : 90,
  formItemList : [
    {
      label : '用户名',
      prop : 'username',
      type : 'input',
    },
    {
      label : '用户昵称：',
      prop : 'nickname',
      type : 'input',
    },
    {
      label : '手机号：',
      prop : 'phone',
      type : 'input',
    },
     {
      label : '密码：',
      prop : 'password',
      type : 'input',
    },
     {
      label : '姓名：',
      prop : 'name',
      type : 'input',
    },
     {
      label : '邮箱：',
      prop : 'email',
      type : 'input',
    },
     {
      label : '角色：',
      prop : 'role',
      placeholder : '请输入',
      type : 'select',
      getSelectList : getSelectList,
      optList : currentOpt.value
    },
     {
      label : '部门：',
      prop : 'deptId',
      type : 'select',
      placeholder : '请输入',
      getSelectList : getSelectOptList,
      optList : currentDept.value
    },
     {
      label : '状态：',
      prop : 'lockFlag',
      type : 'radio',
      optList : [
        {
          label : '启用',
          value : '0'
        },
        {
          label :'禁用',
          value : '9'
        }
      ]
    }
  ]
})

const cancel = () => {
  resetForm(formValue)
  dialogVisible.value = false
}
const dialogTitle = ref('')
const btnList = ref([
  {
    label : '新增',
    func : () => {
      dialogTitle.value = '新增'
      dialogVisible.value = isAdd.value = true
    },
    type : 'warning',
  },
   {
    label : '删除',
    func : () =>{} ,
    type : 'success',
  },
])
const updateFun =(item) => {
    console.log(item);
    delVisible.value = true
}
const deleFun = () => {
  if(currentVisId.value == 1){
    UserService.lockUser(currentName.value).then(res => {
      if(res.code == 0){
        ElMessage.success('操作成功！')
        delVisible.value = false
        getUserData()
      }
    })
  }
}
const detailFun = (item) => {

}
const userId = ref('')
const isAdd = ref(true)
const btnArr = ref([
    {
        label : '修改',
        func : (item) => {
          isAdd.value = false
          const {row} = item
          formValue.userId = row.userId
          formValue.email = row.email
          formValue.lockFlag = row.lockFlag
          formValue.name = row.name
          formValue.nickname = row.nickname
          formValue.phone = row.phone;
          formValue.username = row.username
          formValue.deptId = getLabel(deptList.value,row.deptId)
          
          formValue.role = row.roleList[0].roleName
          dialogTitle.value = '修改'
          dialogVisible.value = true
        },
        type : 'primary'
    },
    {
        label : '删除',
        func : (item) => {
          ElMessageBox.alert('确认删除么？', '删除', {
            confirmButtonText: '确认',
              callback: (action) => {
                UserService.delUser([item.row.userId]).then(res => {
                  if(res.code == 0){
                    ElMessage.success('删除成功!')
                    getUserData()
                  }
                })
              },
            })
          currentVisId.value = 0
          userId.value = item.row.userId
        },
        type : 'danger'
    },
    {
        label : '详情',
        func : detailFun,
        type : 'primary'
    }
])
const tableColumns = ref([
        {type : 'index'},
        {
            label : '用户名称',
            prop : 'username',
        },
        {
            label : '用户昵称',
            prop : 'nickname',
        },
        {
            label : '手机号',
            prop : 'phone',
        },
        {
            label : '状态',
            prop : 'lockFlag',
            slot : 'status',
            width : 200
        },
        {
            label : '创建时间',
            prop : 'createTime',
        },
        {
            label : '操作',
            width:200,
            slot : 'opt'
        },
    ])
const tableData = ref([
])
const getUserData = () => {
  let params = {
    deptId : currentDeptId.value,
    current : page.value,
    size : size.value,
    username : uName.value,
    lockFlag : status.value,
    nickname : nickName.value,
    phone : phone.value
  }
  UserService.getUserList(params).then(res => {
    if(res.code == 0){
      const {records,total} = res.data
      tableData.value = records
      totalData.value = total
    }
  })
}
const searchMenu = ref('')
const handleNodeClick = (value) => {
  let params = {
    deptId : value.id,
    size : 10,
    current : 1
  }
  currentDeptId.value = value.id
  UserService.getUserList(params).then(res => {
    if(res.code == 0){
      const {records,total} = res.data
      tableData.value = records
      totalData.value = total
    }
  })
}
const treeData = ref([])
const defaultProps = {
  children: 'children',
  label: 'name',
}
</script>
<style scoped>
.leftDiv{
    width: 199px;
    height: 93vh;
    border-radius: 2px;
    background-color: rgba(255,255,255,1);
    border: 0px solid rgba(187,187,187,1);
}
.rightDiv{
    width: 88%;
    height: 93vh;
    background-color: rgba(255,255,255,1);
    border: 0px solid rgba(187,187,187,1);
}
</style>